/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package functions;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import model.Catalog;
import model.Database;
import model.Distributor;

/**
 *
 * @author GiK
 */
public class Distributors {

    public static ArrayList<Distributor> getAll() throws SQLException
    {
        Database db = new Database();
        ResultSet set = db.getDBInfo("*", "distributors","");
        ArrayList<Distributor> list = new ArrayList<Distributor>();
        while ( set.next())
        {
            list.add(new Distributor(set.getInt(1),     // id
                              set.getString(2)  // name
                              ));
        }
        db.closeStatement();
        return list;
    }
    public static ArrayList<Distributor> getByName(String name) throws SQLException
    {
        Database db = new Database();
        ResultSet set = db.getDBInfo("*", "distributors","name LIKE '%"+name+"%' " +
                " ORDER BY name != '"+name+"'," +
                "         name not like '"+name+" %'," +
                "         name not like '"+name+"%', name  ");
        ArrayList<Distributor> list = new ArrayList<Distributor>();
        while ( set.next())
        {
            list.add(new Distributor(set.getInt(1),     // id
                              set.getString(2)  // name
                              ));
        }
        db.closeStatement();
        db=null;
        return list;
    }

    public static int addToCatalog(Distributor distr) throws SQLException
    {
        String what="name",values = "";
        if(distr.getName().equals(""))
            throw new SQLException("Введите имя");
        values = "'"+distr.getName() + "'";
        if(distr.getDescr() != null && !distr.getDescr().equals(""))
        {
            what +=",description";
            values +=",'"+distr.getDescr() + "'";
        }
        return Catalog.addDistr(what, values);
    }
    public static int addOtherToCatalog(Distributor distr) throws SQLException
    {
        String what="name",values = "";
        if(distr.getName().equals(""))
            throw new SQLException("Введите имя");
        values = "'"+distr.getName() + "'";
        if(distr.getDescr() != null && !distr.getDescr().equals(""))
        {
            what +=",description";
            values +=",'"+distr.getDescr() + "'";
        }
        return Catalog.addOtherDistr(what, values);
    }
}
